package com.example.libbase.net;

import androidx.lifecycle.LifecycleOwner;

import com.example.libbase.net.exception.ApiException;
import com.example.libbase.net.response.ICallback;
import com.example.libbase.net.response.IResponse;
import com.example.libbase.net.response.ResponseTransformer;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 公用方法
 *
 * @author hermit
 * @date 2021/6/20 0:05
 */
public class RequestModel {

    /**
     * 封装完整的网络请求
     * @param o ApiService中提供网络请求 注解@GET @POST等
     * @param lifecycleOwner 对应的Activity
     * @param callback 回调方法
     * @param <T> 对于返回类型实体
     */
     public static <T> void request(Observable<? extends IResponse<T>> o,
                                    LifecycleOwner lifecycleOwner,
                                    ICallback<T> callback) {
         Disposable d = o.compose(ResponseTransformer.obtain(lifecycleOwner))
                 .subscribe(new Consumer<T>() {
                     @Override
                     public void accept(T t) throws Exception {
                        // RxJava未报错情况下
                         callback.onSuccess(t);
                     }
                 }, new Consumer<Throwable>() {
                     @Override
                     public void accept(Throwable throwable) throws Exception {
                        // 异常情况下 回调失败（包含代码异常和业务逻辑异常）
                         callback.onFailure(ApiException.handleException(throwable));
                     }
                 });

     }
}
